 
import * as excel from './excel'

export interface Book{
    id:number
    bookName:string
    publisher:string
    author:string
    totalCount:number
    availableCount:number
    indexNo:string
}

export type NewBook=Omit<Book,'id'>

export interface ImportOptions{
    skipHeader:boolean
    bookNameCol:string
    authorCol:string
    publisherCol:string
    indexNoCol:string
    totalCountCol:string
    availableCountCol:string
    file:File
}

export interface ImportResult{
    acceptCount:number
    repeatCount:number
    importCount:number
    message:string
}


export async function try_get_books(page_offset:number=0, page_size:number=10){
    const api=`api/books?offset=${page_offset}&count=${page_size}`
    const res = await fetch(api)
    if (res.ok==false) {
        console.error('Get books failed!')
        console.dir(res)
        throw await res.text()
    }
    const books_result:BooksResult= await res.json()
    // console.info('Get books count:',books.length)
    // console.dir(books)
    return books_result;
}

export async function try_get_book_count(){
    const api="api/Books/count"
    const res=await fetch(api)
    if (res.ok==false) {
        console.error('Get books count failed!')
        console.dir(res)
        throw await res.text()
    }
    return parseInt(await res.text())
}

export interface BooksResult{
    totalCount:number,
    pageOffset:number,
    pageSize:number,
    books:Book[],
}

export async function try_search_books(search_type:string, keyword:string,page_offset:number=0,page_size:number=20){
    const api=`/api/books/search?type=${search_type}&keyword=${keyword}&page_offset=${page_offset}&page_size=${page_size}`
    // console.log(api)
    // const url= new URL('api/books/search')
    // url.searchParams.append('type',search_type)
    // url.searchParams.append('keyword',keyword)
    // url.searchParams.append('page_offset',page_offset.toString())
    // url.searchParams.append('page_size',page_size.toString())
    const res= await fetch(api)
    if (res.ok==false){
        // alert('Search books failed!')
        console.warn('Search books failed!')
        console.dir(res)
        throw await res.text()
    }
    const result:BooksResult=await res.json()
    console.log('Get books after search:',result.books.length)
    return result
}


// export async function try_get_new_book_fields(){
//     const api='/api/books/template'
//     const res= await fetch(api)
//     if (res.ok) {
//         return (await res.json()) as Field[]
//     }else{
//         throw await res.text()
//     }
// }

export async function try_post_book(new_book:any){
    console.info(JSON.stringify(new_book))
    const api='/api/books/add'
    const res =await fetch(api,{
        method:'post',
        body:JSON.stringify(new_book),
        headers:{'Content-Type':'application/json;charset=utf-8'}
    })
    if (res.ok==false) {
        console.error('Post new book failed!')
        // console.dir(res)
        throw await res.text();
    }
}







export async function try_parse_books_from_excel(options:Partial<ImportOptions>){
    let sheet:any
    try {
        sheet= await excel.try_get_sheet(options.file!)
    } catch (error) {
        throw '读取工作表失败!'
    }
    // console.dir(sheet)
    let row_idx=options.skipHeader?2:1
    const new_books:NewBook[]=[]
    // console.log('has row:',row_idx,has_row(sheet,row_idx))
    while (excel.has_row(sheet,row_idx)) {
        const new_book:NewBook=Object.create(null)
        new_book.bookName=excel.read_cell(sheet,row_idx,options.bookNameCol)

        if (!new_book.bookName) {
            throw `读取书籍名失败, 行号[${row_idx}]`
        }
        new_book.author=excel.read_cell(sheet,row_idx,options.authorCol)
        new_book.publisher=excel.read_cell(sheet,row_idx,options.publisherCol)
        new_book.indexNo=excel.read_cell(sheet,row_idx,options.indexNoCol)

        // console.log(new_book)

        const total_count_str=excel.read_cell(sheet,row_idx,options.totalCountCol)
        try {
            new_book.totalCount=excel.try_parse_positive_number('书籍总数',total_count_str,row_idx)
        } catch (error) {
            throw error
        }
        const available_count_str=excel.read_cell(sheet,row_idx,options.availableCountCol)
        try {
            new_book.availableCount=excel.try_parse_positive_number('可借数量',available_count_str,row_idx)
        } catch (error) {
            throw error
        }
        if (new_book.availableCount>new_book.totalCount) {
            throw `可借数量[${new_book.availableCount}]不得大于书籍总数[${new_book.totalCount}], 行号[${row_idx}]`
        }
        new_books.push(new_book)
        row_idx++
    }
    return new_books
}


export async function try_post_books(books:NewBook[]){
    const api='/api/books/import'
    // console.dir(books)
    const res =await fetch(api,{
        method:'post',
        body:JSON.stringify(books),
        headers:{'Content-Type':'application/json;charset=utf-8'}
    })
    if (res.ok==false) {
        console.error('Import new books failed!')
        // console.dir(res)
        const error= await res.text()
        throw error
    }
    return (await res.json() as ImportResult)
}

export async function try_delete_book(bid:number) {
    const api='/api/books/delete/'+bid
    const res= await fetch(api,{
        method:'delete'
    })
    if(!res.ok){
        throw await res.text()
    }
    return (await res.json()) as Book
}

export async function try_update_book(bid:number,book:NewBook) {
    const api='/api/books/update/'+bid
    const res =await fetch(api,{
        method:'post',
        body:JSON.stringify(book),
        headers:{'Content-Type':'application/json;charset=utf-8'}
    })
    if (!res.ok) {
        throw await res.text()
    }
    return (await res.json()) as Book
}


export interface BorrowRecord{
    id:number,
    // userID:number,
    bookName:string,
    borrowDate:Date,
    returnDate?:Date,
    [x:string]:any,
}

export interface UserBorrowRecord extends BorrowRecord{
    userName:string,
}

export async function try_borrow_book(bid:number) {
    const api='/api/books/borrow/'+bid
    const res= await fetch(api)
    if (res.ok==false) {
        throw await res.text()
    }
    return (await res.json()) as BorrowRecord
}

export async function try_return_book(rid:number){
    const api='/api/books/return/'+rid
    const res= await fetch(api)
    if (res.ok==false) {
        throw await res.text()
    }
    return (await res.json()) as BorrowRecord
}

export async function try_get_user_records(uid:number|string) {
    const api='/api/books/record/'+uid
    const res= await fetch(api)
    if (res.ok==false) {
        throw await res.text()
    }
    return (await res.json()) as BorrowRecord[]
}

export async function try_get_all_records() {
    const api='/api/books/record/all'
    const res= await fetch(api)
    if (res.ok==false) {
        throw await res.text()
    }
    return (await res.json()) as UserBorrowRecord[]
}

export async function try_delete_records(rid:number) {
    const api='/api/books/record/'+rid
    const res= await fetch(api,{method:'delete'})
    if (res.ok==false) {
        throw await res.text()
    }
    // return (await res.json()) as BorrowRecord
}